import type { ReadingQuestionGroupDetail } from '@/request/teacher/bank'
import { ref } from 'vue'
import message from '@/components/common/message'
import { getClassList } from '@/request/class'
import { createOrUpdateHomework, getHomeworkDetail } from '@/request/teacher/homework'
import { useTeacherStore } from '@/store/teacher'

export function useHomework(homeworkId?: string, exitedReadingId?: string, exitedReadingTitle?: string) {
  const date = new Date()
  date.setMilliseconds(0)
  const homeworkDeadline = ref(date)
  const homewokrTilte = ref(exitedReadingTitle || '')
  const homeworkClassId = ref('')
  const homeworkContent = ref(exitedReadingTitle ? `完成 ${exitedReadingTitle}` : '')
  const selectedReadingId = ref('')
  const avaliableClassList = ref<{ label: string, value: string }[]>([])
  const avaliableQuestionGroupList = ref<{ label: string, value: string }[]>([])
  const readingId = ref(exitedReadingId)
  const isLoading = ref(false)
  if (homeworkId) {
    isLoading.value = true
    getHomeworkDetail({ homeworkId })
      .then((data) => {
        homewokrTilte.value = data.entry.title
        homeworkClassId.value = data.entry.classId || ''
        homeworkContent.value = data.entry.description
        homeworkDeadline.value = new Date(data.entry.deadline)
        exitedReadingId
          ? void 0
          : readingId.value = data.entry.readingId
      })
      .finally(() => {
        isLoading.value = false
      })
  }
  const teacherStore = useTeacherStore()
  const loadClassList = async () => {
    const data = await getClassList({
      school: teacherStore.teacher.school,
    })
    avaliableClassList.value = data.entries.flatMap(entry =>
      entry.classes.map(cls => ({ label: cls.name, value: cls.cid })),
    )
  }
  loadClassList()
  const saveHomework = async (readingDetail?: ReadingQuestionGroupDetail) => {
    try {
      await createOrUpdateHomework({
        classId: homeworkClassId.value,
        description: homeworkContent.value,
        deadline: homeworkDeadline.value.toISOString(),
        homeworkId,
        title: homewokrTilte.value,
        readingId: exitedReadingId,
        readingDetails: readingDetail,
      })
      message.success('保存成功')
    }
    catch (error) {
      console.error('保存失败:', error)
      message.error('保存失败')
      throw new Error('保存作业失败')
    }
  }

  return {
    homewokrTilte,
    homeworkClassId,
    homeworkDeadline,
    homeworkContent,
    selectedReadingId,
    avaliableClassList,
    avaliableQuestionGroupList,
    readingId,
    isLoading,
    saveHomework,
  }
}
